import axios from "axios";
import router from "@/router";
import { ElMessage } from "element-plus";
//创建axios实例
const request = axios.create({
  baseURL: '/api',
  timeout: 500000
})
//axiso请求拦截器,每次请求获取LocalStorage中的loginUserInfo，从中获取token，在请求头中携带token带到服务器
request.interceptors.request.use( config => {
  let loginUserInfo = JSON.parse(localStorage.getItem('loginUserInfo'))
  if (loginUserInfo) {
    config.headers.token = loginUserInfo.token
  }
  return config
})
//axios响应拦截器
request.interceptors.response.use(
  response => {//成功回调
    return response.data
  },
  error => {//失败回调
    if (error.response.status === 401) {
      ElMessage.error('登录信息已过期，请重新登录')
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

export default request;
